package com.jeomo.base.starter.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.jeomo.common.core.util.StringUtils;
import com.jeomo.shiro.dto.LoginInfo;
import com.jeomo.shiro.util.LoginSessionUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
/**
 * 数据回填信息
 */
public class MyMetaObjectHandler implements MetaObjectHandler {

    Logger logger = LoggerFactory.getLogger(MyMetaObjectHandler.class);

    final String FIELD_CREATE_VERSION = "version";

    final String FIELD_CREATE_TIME_NAME = "createTime";

    final String FIELD_CREATE_USER_NAME = "createUser";

    final String FIELD_MODIFY_TIME_NAME = "lastModifyTime";

    final String FIELD_MODIFY_USER_NAME = "lastModifyUser";


    @Override
    public void insertFill(MetaObject metaObject) {
        logger.debug("插入时自动填充数据..");
        this.strictInsertFill(metaObject, FIELD_CREATE_TIME_NAME, Date.class, new Date());
        setCreateOrModifyUser(metaObject, FIELD_CREATE_USER_NAME);
        setFieldValByName(FIELD_CREATE_VERSION,System.currentTimeMillis(),metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        logger.debug("修改时自动填充数据..");
        this.strictUpdateFill(metaObject, FIELD_MODIFY_TIME_NAME, Date.class, new Date());
        setCreateOrModifyUser(metaObject, FIELD_MODIFY_USER_NAME);
    }

    private void setCreateOrModifyUser(MetaObject metaObject, String fileName) {
        LoginInfo loginInfo = LoginSessionUtil.getCurrentLoginInfo();
        if(loginInfo != null && StringUtils.isNotEmpty(loginInfo.getUsername())) {
            this.strictInsertFill(metaObject, fileName, String.class, loginInfo.getUsername());
        } else {
            this.strictInsertFill(metaObject, fileName, String.class, "admin");
        }
    }

}
